package runnable;

import java.util.concurrent.TimeUnit;

/**
 * @classname:SaleTest
 * @description:
 * @author: Mr.Z
 * @date: 2020/12/18 23:52
 * @version: 0.1
 * @since:1.8
 */
public class SaleTicket {
    private Integer ticketNum = 30;
    //同步代码块
 /*   public void saleTicket() {
        while (ticketNum > 0) {
            synchronized ("锁") {
                if (ticketNum > 0) {
                    System.out.println(Thread.currentThread().getName() + "正在出售第" + ticketNum-- + "张票");
                    try {
                        TimeUnit.MILLISECONDS.sleep(300);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }

                }
            }
        }
    }*/


 //方法锁
    public void saleTicket() {
        while (ticketNum > 0) {
         a();
        }
    }

    public synchronized void a() {
        if(ticketNum>0){
            System.out.println(Thread.currentThread().getName() + "正在出售第" + ticketNum-- + "张票");
            try {
                TimeUnit.MILLISECONDS.sleep(300);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }

    }
}
